"use client"

import { ScrollView, StyleSheet, View, Text, TouchableOpacity, Platform, Image } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { StatusBar } from "expo-status-bar"
import { BookSection } from "../../components/vocabulary/BookSection"
import { LinearGradient } from "expo-linear-gradient"
import { theme } from "../../constants/theme"
import { useRouter, useFocusEffect } from "expo-router"
import { useState, useCallback } from "react"
import AsyncStorage from "@react-native-async-storage/async-storage"

export default function VocabularyScreen() {
    const router = useRouter()

    // 默认书本数据
    const defaultBook = {
        title: "人教PEP版",
        subtitle: "一年级上册（新课标版）",
        mastered: 5,
        learning: 8,
        total: 21,
    }

    // 状态管理当前书本
    const [currentBook, setCurrentBook] = useState(defaultBook)

    // 使用 useFocusEffect 确保每次页面获得焦点时都检查是否有新的书籍数据
    useFocusEffect(
        useCallback(() => {
            const loadSelectedBook = async () => {
                try {
                    const bookData = await AsyncStorage.getItem("selectedBook")
                    if (bookData) {
                        const selectedBook = JSON.parse(bookData)
                        console.log("加载选中的书籍:", selectedBook)
                        setCurrentBook(selectedBook)
                        // 读取后清除，避免下次进入页面时仍然显示
                        await AsyncStorage.removeItem("selectedBook")
                    }
                } catch (error) {
                    console.error("读取选中书籍数据失败:", error)
                }
            }

            loadSelectedBook()
        }, []),
    )

    const handleBookPress = () => {
        console.log("Book pressed")
    }

    const handleDetailsPress = () => {
        router.push('/learning-details-screen')
        console.log("Details pressed")
    }

    const handleSearchPress = () => {
        // 确保导航到搜索页面
        router.push("/search-screen")
    }

    const handleBookListPress = () => {
        router.push("/books-screen")
    }

    const handleWordAffixPress = () => {
        // 传递当前书籍名称
        router.push({
            pathname: "/word-affix-screen",
            params: { bookTitle: currentBook.title },
        })
    }

    // Add this function to handle the click on "音标组" button
    const handlePhoneticGroupPress = () => {
        // 传递当前书籍名称
        router.push({
            pathname: "/phonetic-symbols-screen",
            params: { bookTitle: currentBook.title },
        })
    }

    // Add this function to handle the click on "收藏本" button
    const handleFavoritesPress = () => {
        router.push("/favorites-screen")
    }

    return (
        <>
            <StatusBar style="dark" />
            <SafeAreaView style={styles.container} edges={["top"]}>
                <LinearGradient
                    colors={theme.colors.neutral.backgroundGradient}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 0, y: 1 }}
                    style={styles.gradientBackground}
                >
                    <ScrollView
                        style={styles.scrollView}
                        contentContainerStyle={styles.scrollContent}
                        showsVerticalScrollIndicator={false}
                    >
                        <BookSection
                            book={currentBook}
                            onBookPress={handleBookPress}
                            onDetailsPress={handleDetailsPress}
                            onSearchPress={handleSearchPress}
                            onBookListPress={handleBookListPress}
                        />

                        {/* 操作按钮 */}
                        <View style={styles.actionButtonsContainer}>
                            <TouchableOpacity style={styles.primaryButton} onPress={() => router.push("/learning-screen")}>
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 1 }}
                                    style={styles.gradientButton}
                                >
                                    <Image
                                        source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341025.png" }}
                                        style={[styles.buttonIcon, { tintColor: theme.colors.neutral.white }]}
                                    />
                                    <Text style={styles.primaryButtonText}>开始学习</Text>
                                </LinearGradient>
                            </TouchableOpacity>

                            <TouchableOpacity
                                style={styles.secondaryButton}
                                onPress={() => router.push("/learning-screen?mode=review")}
                            >
                                <Image
                                    source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341139.png" }}
                                    style={[styles.buttonIcon, { tintColor: theme.colors.primary.default }]}
                                />
                                <Text style={[styles.secondaryButtonText, { color: theme.colors.primary.default }]}>复习单词</Text>
                            </TouchableOpacity>
                        </View>

                        {/* 学习模式 */}
                        <View style={styles.learningModesContainer}>
                            <View style={styles.sectionTitleContainer}>
                                <Image
                                    source={{ uri: "https://cdn-icons-png.flaticon.com/512/3135/3135755.png" }}
                                    style={styles.sectionIcon}
                                />
                                <Text style={styles.sectionTitle}>学习模式</Text>
                                <View style={styles.titleLine} />
                            </View>

                            <View style={styles.modesContainer}>
                                <TouchableOpacity style={styles.modeCard} onPress={() => router.push("/natural-reading-screen")}>
                                    <View style={[styles.modeIconContainer, { backgroundColor: theme.colors.secondary.green.light }]}>
                                        <Text style={styles.letterIcon}>Aa</Text>
                                    </View>
                                    <Text style={styles.modeText}>自然拼读</Text>
                                </TouchableOpacity>

                                <TouchableOpacity style={styles.modeCard} onPress={handleWordAffixPress}>
                                    <View style={[styles.modeIconContainer, { backgroundColor: theme.colors.secondary.orange.light }]}>
                                        <Text style={[styles.letterIcon, { color: theme.colors.secondary.orange.default }]}>En</Text>
                                    </View>
                                    <Text style={styles.modeText}>词根词缀</Text>
                                </TouchableOpacity>

                                <TouchableOpacity style={styles.modeCard} onPress={handlePhoneticGroupPress}>
                                    <View style={[styles.modeIconContainer, { backgroundColor: theme.colors.neutral.background }]}>
                                        <Text style={[styles.letterIcon, { color: theme.colors.primary.default }]}>[æ]</Text>
                                    </View>
                                    <Text style={styles.modeText}>音标组</Text>
                                </TouchableOpacity>
                            </View>
                        </View>

                        {/* 底部操作 */}
                        <View style={styles.bottomActionsContainer}>
                            <TouchableOpacity style={styles.actionButton} onPress={handleFavoritesPress}>
                                <View style={[styles.actionIconContainer, { backgroundColor: theme.colors.secondary.orange.light }]}>
                                    <Image
                                        source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341050.png" }}
                                        style={[styles.actionIcon, { tintColor: theme.colors.secondary.orange.default }]}
                                    />
                                </View>
                                <Text style={styles.actionText}>收藏本</Text>
                            </TouchableOpacity>

                            <TouchableOpacity style={styles.actionButton} onPress={() => router.push("/wrong-words-screen")}>
                                <View style={[styles.actionIconContainer, { backgroundColor: theme.colors.neutral.background }]}>
                                    <Image
                                        source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341102.png" }}
                                        style={[styles.actionIcon, { tintColor: theme.colors.primary.default }]}
                                    />
                                </View>
                                <Text style={styles.actionText}>错题本</Text>
                            </TouchableOpacity>
                        </View>

                        <View style={styles.bottomSpacing} />
                    </ScrollView>
                </LinearGradient>
            </SafeAreaView>
        </>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    scrollView: {
        flex: 1,
    },
    scrollContent: {
        paddingBottom: 100,
    },

    // 操作按钮样式
    actionButtonsContainer: {
        flexDirection: "row",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
        gap: theme.spacing.md,
    },
    primaryButton: {
        flex: 1,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 5,
            },
        }),
    },
    gradientButton: {
        paddingVertical: theme.spacing.lg,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        borderRadius: theme.borderRadius.large,
    },
    secondaryButton: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        paddingVertical: theme.spacing.lg,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        borderWidth: 1.5,
        borderColor: theme.colors.primary.default,
        ...Platform.select(theme.shadows.small),
    },
    buttonIcon: {
        width: 24,
        height: 24,
        marginRight: theme.spacing.sm,
    },
    primaryButtonText: {
        color: theme.colors.neutral.white,
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
    },
    secondaryButtonText: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
    },

    // 学习模式样式
    learningModesContainer: {
        padding: theme.spacing.lg,
    },
    sectionTitleContainer: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: theme.spacing.lg,
    },
    sectionIcon: {
        width: 24,
        height: 24,
        marginRight: theme.spacing.sm,
    },
    sectionTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginRight: theme.spacing.md,
    },
    titleLine: {
        flex: 1,
        height: 1,
        backgroundColor: `${theme.colors.primary.default}30`,
    },
    modesContainer: {
        flexDirection: "row",
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge,
        padding: theme.spacing.xl,
        gap: theme.spacing.lg,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.2,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    modeCard: {
        flex: 1,
        alignItems: "center",
        gap: theme.spacing.md,
    },
    modeIconContainer: {
        width: 56,
        height: 56,
        borderRadius: 28,
        alignItems: "center",
        justifyContent: "center",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.2,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    letterIcon: {
        fontSize: 22,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.secondary.green.default,
    },
    modeText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.black,
        fontWeight: theme.fontWeight.medium,
    },

    // 底部操作样式
    bottomActionsContainer: {
        flexDirection: "row",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
        gap: theme.spacing.md,
    },
    actionButton: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        flexDirection: "row",
        alignItems: "center",
        gap: theme.spacing.md,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.2,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    actionIconContainer: {
        width: 44,
        height: 44,
        borderRadius: 22,
        alignItems: "center",
        justifyContent: "center",
    },
    actionIcon: {
        width: 22,
        height: 22,
    },
    actionText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.black,
        fontWeight: theme.fontWeight.medium,
    },

    bottomSpacing: {
        height: 20,
    },
})

